package com.lepu.app.fun.index.activity;

import java.util.ArrayList;

import android.app.AlarmManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.DateUtil;
import com.app.utils.ObserverConst;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UIHelper;
import com.lepu.app.fun.index.adapter.IndexRemindAddAdapter;
import com.lepu.app.fun.index.remind.Alarm;
import com.lepu.app.fun.index.remind.AlarmTipsManager;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

public class IndexRemindAddActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener {

	private EditText mDrugEditText;
	private EditText mUsageEditText;
	
	private ListView mDataListView;
	private IndexRemindAddAdapter mAdapter;
	private ArrayList<String> mTimeList;
	
	private static IndexRemindAddActivity instance;
	
	private AlarmManager alarmManager;

	private boolean isSave = true;  //保存 or 更新
	private Alarm alarm = null;
	private ArrayList<Alarm> alarmList = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index_remind_add_activity);
		instance = this;
		init();
	}

	@Override
	public void onResume() {
		super.onResume();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		instance = null;
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarRightButtonSelected() {
		doSave();
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	public static IndexRemindAddActivity getInstance(){
		return instance;
	}
	
	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setRightText("完成");
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setOnTopbarNewRightButtonListener(this);

		mDrugEditText = (EditText) findViewById(R.id.drugEditText);
		mUsageEditText = (EditText) findViewById(R.id.usageEditText);
		mDataListView = (ListView) findViewById(R.id.dataListView);

		TextView addTextView = (TextView) findViewById(R.id.addTextView);
		addTextView.setOnClickListener(onClick);
		
		Intent intent = this.getIntent(); 
		alarm=(Alarm)intent.getSerializableExtra("alarm");
		
		if(alarm != null){ //不为null 为编辑
			isSave = false;
		}
		
		mTimeList = new ArrayList<String>();
		
		if(isSave){
			mTimeList.add(DateUtil.customTime("HH:mm"));
		}else{
			mDrugEditText.setText(alarm.yaoName);
			mUsageEditText.setText(alarm.yaoType);
			
			alarmList = AlarmTipsManager.getAlarmByName(alarm.yaoName);
			for (Alarm alarm : alarmList) {
				mTimeList.add(alarm.time);
			}
		}
		
		mAdapter = new IndexRemindAddAdapter(this, mTimeList);
		mDataListView.setAdapter(mAdapter);
		
		alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
	}

	View.OnClickListener onClick = new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			if(mTimeList.size() < 4){
				mTimeList.add(DateUtil.customTime("HH:mm"));
				mAdapter.notifyDataSetChanged();
			}
		}
	};
	
	public void deleteItem(int position){
		mTimeList.remove(position);
		mAdapter.notifyDataSetChanged();
	}
	
	 /**
     * 存储数据库，并且进行闹钟设置（默认每天都提醒）
     */
    public void doSave() {
        if (mDrugEditText == null || mDrugEditText.getText().toString().trim().equals("")) {
            UIHelper.showToast(this, "请输入药品名称！");
            return;
        }
        if (mDrugEditText.getText().toString().length() > 30) {
            UIHelper.showToast(this, "药品名称不能超过30个字");
            return;
        }
        
        if (mUsageEditText == null || mUsageEditText.getText().toString().trim().equals("")) {
            UIHelper.showToast(this, "请输入用法用量！");
            return;
        }
        
        if(!isSave){  //更新
            /**
             * 取消之前的定时，并删除数据库中数据，重新进行定时的任务
             * 1.取消
             * 2.刪除
             */
            for (Alarm alarm : alarmList) {
                Alarm.closeRemind(MyApplication.alarmManager, this, alarm.alarmId);
                AlarmTipsManager.deleteItem(alarm.alarmId); 
            }
        }
        
        String medicationName = mDrugEditText.getText().toString().trim();
        boolean isExit = AlarmTipsManager.getInstance().isExist(medicationName);
        if (isExit) {
        	UIHelper.showToast(this, "已经存在该药品名称的提醒！");
            return;
        }
        
        showProgressDialog();
        Alarm alarm = new Alarm();
        for (int k = 0; k < mTimeList.size(); k++) {
            if (mTimeList.get(k) != null) {
                int day = 0;
                String yearMonthDay = DateUtil.getNowDate(DateUtil.YEAR_MONTH_DAY);
                alarm.type = Alarm.TYPE_YAO;
                alarm.alarmTime = DateUtil.getLongOfDayTimeAll(yearMonthDay, mTimeList.get(k)) + day * DateUtil.DAY_MILLIS;
                alarm.setTime = DateUtil.getNowTimeInMillis();
                alarm.time = mTimeList.get(k);
                alarm.week = "";
                alarm.isRepeat = true;
                alarm.repeatTime = DateUtil.DAY_MILLIS;//每天都进行循环
                alarm.yaoName = medicationName; //药品名称
                alarm.yaoType = mUsageEditText.getText().toString().trim(); //用法用量
                alarm.userid = "";
                Alarm.setRemind(alarm, alarmManager, this);
            }
        }
        hideProgressDialog();
        ObserverManager.getInstance().notify(ObserverConst.NOTIFY_REMIND_CHANGE, null,null);
        finish(true);
    }
}
